package bluetooth.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import bluetooth.data.DataFactory;
import bluetooth.data.DeserializeData;
import bluetooth.stat.StaticData;

import com.urbanairship.Logger;
import com.urbanairship.UAirship;
import com.urbanairship.analytics.InstrumentedActivity;
import com.urbanairship.push.PushManager;



public class MainActivity extends InstrumentedActivity implements View.OnClickListener {

	private ProgressDialog progressDialog;
	
	private void init (){
		
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle("Please wait...");
		progressDialog.setCancelable(false);

	}

	      //Push notification object
	      private IntentFilter apidUpdateFilter;
		  private static final int REQUEST_ENABLE_BT = 1;
		  private BluetoothAdapter btAdapter = null;
		  private BluetoothSocket btSocket = null;
		  private OutputStream outStream = null;
		  
		  private ImageButton btnConnect;
		 
		  private String msg;
		  
		  @Override
		  public void onCreate(Bundle savedInstanceState) {  
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.activity_main);
		    btnConnect=(ImageButton)findViewById(R.id.btnConnectToServer);
		    btnConnect.setOnClickListener(this);
		   
		  }

		private void initBluetooth (){
			
			 btAdapter = BluetoothAdapter.getDefaultAdapter();
			 CheckBTState();
			// Set up a pointer to the remote node using it's address.
		    BluetoothDevice device =  btAdapter.getRemoteDevice(StaticData.MAC_ADDRESS);
			
		    try {
			     btSocket = device.createRfcommSocketToServiceRecord(StaticData.SERVER_UUID);
			       // btSocket=  device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
			    } catch (final IOException e) {
			    	
			    	this.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							  AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
						}
					});
			   
			    }
			    // Discovery is resource intensive.  Make sure it isn't going on
			    // when you attempt to connect and pass your message.
			    btAdapter.cancelDiscovery();
		}
		
		
		@Override
		public void onResume() {
		    super.onResume();
		    init ();
		    initAirpush();
		  }
		  
		
		  private void sendDataToServer () {
			  
			  this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					progressDialog.show();
				}
			});
			   
			  // Establish the connection.  This will block until it connects.
			    try {
			      btSocket.connect();
			     // out.append("\n...Connection established and data link opened...");
			    } catch (IOException e) {
			      try {
			        btSocket.close();
			      } catch (IOException e2) {
			        AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
			      }
			    }

			    // Create a data stream so we can talk to server.
			    //out.append("\n...Sending message to server...");
			   // String message = "Hello from Android.\n";
			    String message=DataFactory.getJsonData();
			   // out.append("\n\n...The message that we will send to the server is: "+message);

			    try {
			      outStream = btSocket.getOutputStream();
			    } catch (IOException e) {
			      AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
			    }

			    byte[] msgBuffer = message.getBytes();
			    try {
			      outStream.write(msgBuffer);
			    } catch (IOException e) {
			      msg= "In onResume() and an exception occurred during write: " + e.getMessage();
			      if (StaticData.MAC_ADDRESS.equals("00:00:00:00:00:00")) 
			        msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
			      msg = msg +  ".\n\nCheck that the SPP UUID: " + StaticData.SERVER_UUID.toString() + " exists on server.\n\n";

			      this.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						 AlertBox("Fatal Error", msg);  
					}
				});
			          
			    }
			  
		  }

		  private void getDataFromServer  () {
			  
			  //out.append("\n...Hello\n");
			    InputStream inStream;
			    try {
			        inStream = btSocket.getInputStream();
			        BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
			        String lineRead=bReader.readLine();
			       // out.append("\n..."+lineRead+"\n");
			      // DeserializeData.setJsonData(lineRead);
                   //DeserializeData.deserializeJsonData(lineRead)
			        
			    } catch (IOException e) {
			        // TODO Auto-generated catch block
			        e.printStackTrace();
			    }


			  
			  if (outStream != null) {
			      try {
			        outStream.flush();
			      } catch (IOException e) {
			        AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
			      }
			    }

			    try     {
			      btSocket.close();
			    } catch (IOException e2) {
			      AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
			    } 
		  }
		  
		
		  private void CheckBTState() {
		    // Check for Bluetooth support and then check to make sure it is turned on

		    // Emulator doesn't support Bluetooth and will return null
		    if(btAdapter==null) { 
		      AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
		    } else {
		      if (btAdapter.isEnabled()) {
		        //out.append("\n...Bluetooth is enabled...");
		      } else {
		        //Prompt user to turn on Bluetooth
		        Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
		        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		      }
		    }
		  }

		  public void AlertBox( String title, String message ){
		    new AlertDialog.Builder(this)
		    .setTitle( title )
		    .setMessage( message + " Press OK to exit." )
		    .setPositiveButton("OK", new OnClickListener() {
		        public void onClick(DialogInterface arg0, int arg1) {
		          
		        	
		        }
		    }).show();
		  }

		@Override
		public void onClick(View v) {
			
			 if(v==btnConnect){
				
				new ConnectToBluetoothServerTask().execute();
				
			}
			
		}
		
		    @Override
		    public void onPause() {
		        super.onPause();
		        try {
		           // unregisterReceiver(boundServiceReceiver);
		            unregisterReceiver(apidUpdateReceiver);
		        } catch (IllegalArgumentException e) {
		            Logger.error(e.getMessage());
		        }
		    }

		    private BroadcastReceiver apidUpdateReceiver = new BroadcastReceiver() {
		        @Override
		        public void onReceive(Context context, Intent intent) {
		            updateApidField();
		        }
		    };

		    private void updateApidField() {
		        String apidString = PushManager.shared().getAPID();
		        Toast.makeText(this,"apid:"+ apidString, 5000).show();
		        if (!PushManager.shared().getPreferences().isPushEnabled() || apidString == null) {
		            apidString = "";
		        }
		        
		        Toast.makeText(this,"apid:"+ apidString, 5000).show();
		        StaticData.APID=apidString;
		    }
		    
		   
		    
	private void initAirpush (){
		
		    apidUpdateFilter = new IntentFilter();
	        apidUpdateFilter.addAction(UAirship.getPackageName()+IntentReceiver.APID_UPDATED_ACTION_SUFFIX);
	        // OPTIONAL! The following block of code removes all notifications from the status bar.
	        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	        notificationManager.cancelAll();
	        registerReceiver(apidUpdateReceiver, apidUpdateFilter);
	        updateApidField();
	}  
	
	
	private class ConnectToBluetoothServerTask extends  AsyncTask<Object, Object, Object>{
		@Override
		protected Object doInBackground(Object... params) {
			
			try{
				
				initBluetooth();
				sendDataToServer();
			    getDataFromServer();
			}catch (Exception ex){
				
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progressDialog.hide();
		}
		
		
		
	}
	 
}




